<template>
  <div class="top-category">
    <div class="container">
        <!-- 面包屑导航 -->
        <!-- 面包屑 -->
<XtxBread>
   <XtxBreadItem to="/">首页</XtxBreadItem>
   <XtxBreadItem>{{categroyName.name}}</XtxBreadItem>
</XtxBread>
      <!-- 轮播图 -->
      <XtxSlider :sliders="sliderList" :autoPlay="true" style="height:500px"/>
    <!-- 所有二级分类 -->
     <div class="sub-list">
    <h3>全部分类</h3>
    <ul>
      <li v-for="i in categroyAllList" :key="i.id">
        <a href="javascript:;">
          <img :src="i.picture" >
          <p>{{i.name}}</p>
        </a>
      </li>
    </ul>
     </div>
<!-- 分类关联商品 -->
     <div class="ref-goods" v-for="item in categroyAllList" :key="item.id">
    <div class="head">
      <h3>-  {{item.name}}  -</h3>
      <XtxMore to="/" />
    </div>
    <div class="body">
<GoodsItem v-for="good in item.goods" :good="good" :key="good.id"/>
    </div>
     </div>
    </div>
  </div>
</template>
<script>
import { findBanner } from '@/api/home'
import { ref, onMounted, watch } from 'vue'
import { findTopCategory } from '@/api/category'
import { useRoute } from 'vue-router'
import GoodsItem from './components/goods-item'
export default {
  name: 'TopCategory',
  components: { GoodsItem },
  setup () {
    // banner功能
    const sliderList = ref([])
    async function getBanner () {
      const res = await findBanner()
      sliderList.value = res.data.result
    }
    onMounted(() => {
      getBanner()
    })
    // 全部分类逻辑实现
    const categroyAllList = ref([])
    const route = useRoute()
    const categroyName = ref('')
    async function getCategoryAllList () {
      const res = await findTopCategory(route.params.id)
      categroyAllList.value = res.data.result.children
      categroyName.value = res.data.result.name
    }
    onMounted(() => {
      getCategoryAllList()
    })
    // 解决路由变化数据不更新问题
    // 原因：vue中路由的复用机制path不发生变化的时候path对应的组件不会进行重新渲染，导致onMouted函数不会再次执行
    // 技术实现：用监听
    watch(
      () => { return route.params.id },
      () => { getCategoryAllList() }
    )
    return {
      sliderList,
      categroyAllList,
      categroyName
    }
  }
}
</script>
<style scoped lang="less">
.top-category {
  h3 {
    font-size: 28px;
    color: #666;
    font-weight: normal;
    text-align: center;
    line-height: 100px;
  }
  .sub-list {
    margin-top: 20px;
    background-color: #fff;
    ul {
      display: flex;
      padding: 0 32px;
      flex-wrap: wrap;
      li {
        width: 168px;
        height: 160px;
        a {
          text-align: center;
          display: block;
          font-size: 16px;
          img {
            width: 100px;
            height: 100px;
          }
          p {
            line-height: 40px;
          }
          &:hover {
            color: @xtxColor;
          }
        }
      }
    }
  }
  .body {
      display: flex;
      justify-content: space-between;
  }

}
</style>
